package handlers

import (
	"effi-manage/cache"
	"effi-manage/model"
	"effi-manage/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"mag":  "字段不能为空",
		})
		return
	}
	redis_key := "redis_err_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 400,
			"mag":  "密码错误3次，禁止登录",
		})
		return
	}
	var user model.User
	err := model.DB.Where("username = ?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"mag":  "查询用户失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"mag":  "账户或密码错误",
		})
		return
	}
	if user.Password != pkg.Str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"mag":  "密码错误3次，封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 400,
			"mag":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"mag":  "登录成功",
		"user": user,
	})
	return

}

func AddUserRole(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	data := model.UserRole{
		Uid: uid,
		Rid: rid,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func RoleNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := model.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func UserroleList(c *gin.Context) {
	uid := c.Query("uid")
	var role []model.Role
	/*
		SELECT * FROM roles
		LEFT JOIN user_roles ON user_roles.rid=roles.id
		WHERE user_roles.uid = 1
	*/
	model.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.rid=roles.id").
		Where("user_roles.uid = ?", uid).
		Find(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": role,
	})
	return
}

func RoleNodeList(c *gin.Context) {
	rid := c.Query("rid")
	var node []model.Node
	/*
		SELECT * FROM nodes
		LEFT JOIN role_nodes ON role_nodes.rid =nodes.id
		WHERE role_nodes.rid =1
	*/
	model.DB.
		Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.rid =nodes.id").
		Where("role_nodes.rid = ?", rid).
		Find(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": node,
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var user []model.User
	redis_key := "redis_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Find(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}
	var count int64
	model.DB.Model(&model.User{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  user,
		"count": count,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var user model.User
	redis_key := "redis_det_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id = ?", id).Find(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": user,
	})
	return
}
